<template>
      <div class="assignment-header">
        <el-button @click="$router.go(-1)" link class="back-button">
          <img src="@/assets/svgs/left.svg" alt="Back" class="back-icon" />
        </el-button>
        <div class="information">HappyfeChat</div>
        <div class="user-info" @click="toggleDropdown">
            <img class="avatar" :src="userInfo?.avatarUrl" alt="User Avatar">
            <span class="username22">{{ userInfo?.nick_name }}</span>
            <img class="dropdown-arrow" src="@/assets/svgs/downnarrow.svg" alt="Dropdown Arrow">
            <div v-if="dropdownVisible" class="dropdown-menu">
                <p @click="$router.push('/teacher/information')">个人信息</p>
                <p @click="$router.push('/login')">退出登录</p>
            </div>
        </div>
    </div>
  <div class="chat-panel">
    <div class="message-panel" id="message-panel">
      <div class="message-list">
        <div
          :class="['message-item', item.type == 1 ? 'ai-item' : '']"
          v-for="(item, index) in messageList"
          :id="'item' + index"
        >
          <template v-if="item.type == 0">
            <div class="message-content">
              <div class="content-inner">{{ item.content }}</div>
            </div>
            <div class="user-icon">我</div>
          </template>
          <template v-else>
            <div class="user-icon">AI</div>
            <div class="message-content ai-item">
              <MdPreview
                previewTheme="vuepress"
                :codeFoldable="false"
                editorId="preview"
                :modelValue="item.content.join('')"
              />
              <div class="loading" v-if="item.loading">
                <img src="@/assets/loading.gif" />
              </div>
            </div>
          </template>
        </div>
      </div>
    </div>
    <div class="send-panel">
      <el-form :model="formData" ref="formDataRef" @submit.prevent>
        <!--input输入-->
        <el-form-item label="" prop="content">
          <el-input
            type="textarea"
            :rows="3"
            clearable
            placeholder="请输入你想问的问题"
            v-model="formData.content"
            @keyup="keySend"
          ></el-input>
        </el-form-item>
        <!--input输入-->
        <el-form-item label="" prop="" class="send-btn">
          <el-button type="primary" @click="sendMessage" :disabled="loading"
            >发送(ctrl+enter)</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script setup>
import { ElMessage } from 'element-plus';
import { informationService } from '@/api/personnal-information';
// 定义响应式数据

const userInfo = ref(null);

const fetchUserInfo = async () => {
    try {
        const result = await informationService();
        const userData = result.data; // 假设后端返回的数据结构是 { data: SysUser }
        userInfo.value = {
            userId: userData.userId,
            avatarUrl: userData.avatar,
            user_name: userData.userName,
            nick_name: userData.nickName
        };
    } catch (error) {
        console.error('获取用户信息失败:', result.message);
    }
};
fetchUserInfo();

import {
  ref,
  reactive,
  getCurrentInstance,
  nextTick,
  onMounted,
  onUnmounted,
} from 'vue';
const { proxy } = getCurrentInstance();
import { MdPreview, MdCatalog } from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';

const formData = ref({});
const messageList = ref([]);
const loading = ref(false);

const keySend = (event) => {
  if (!(event.ctrlKey && event.key === 'Enter')) {
    return;
  }
  sendMessage();
};

const sendMessage = async () => {
    const message = formData.value.content;
    if (!message) {
        ElMessage({
            type: 'warning',
            message: '请输入内容',
            duration: 2000,
        });
        return;
    }
    messageList.value.push({
        type: 0,
        content: message,
    });

    messageList.value.push({
        type: 1,
        content: [],
        loading: true,
    });
    loading.value = true;

    const token = localStorage.getItem('token');
    const url = `/api/stream?message=${message}`;
    console.log('token', token);

    const headers = {
        Authorization: token
    };
    console.log('Request Headers:', headers);

    // 定义 close 函数
    const close = () => {
        messageList.value[messageList.value.length - 1].loading = false;
        loading.value = false;
    };

    try {
        const response = await fetch(url, {
            headers,
            method: 'GET',
            cache: 'no-cache'
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const reader = response.body.getReader();
        const decoder = new TextDecoder('utf-8');
        while (true) {
            const { done, value } = await reader.read();
            if (done) {
                break;
            }
            const chunk = decoder.decode(value);
            const lines = chunk.split('\n');
            for (const line of lines) {
                if (line.trim()) {
                    const data = line.replace('data:', '');
                    if (data === 'end') {
                        close();
                        return;
                    }
                    const responseData = JSON.parse(data).content;
                    messageList.value[messageList.value.length - 1].content.push(responseData);
                    nextTick(() => {
                        const content = document.getElementById('message-panel');
                        content.scrollTop = content.scrollHeight;
                    });
                }
            }
        }
    } catch (error) {
        console.error('Error:', error);
        close();
    }
};
</script>

<style lang="scss" scoped>
.chat-panel {
  background: #eff0f6;
  height: calc(90vh);
  .chat-title {
    text-align: center;
    font-size: 20px;
    font-weight: bold;
  }
  .message-panel {
    position: relative;
    height: calc(90vh - 200px);
    overflow: auto;
    padding-bottom: 10px;
    .message-list {
      margin: 0px auto;
      width: 800px;
      .message-item {
        margin: 10px 0px;
        display: flex;
        .user-icon {
          width: 40px;
          height: 40px;
          line-height: 40px;
          border-radius: 20px;
          background: #535353;
          color: #fff;
          text-align: center;
          margin-left: 10px;
        }
        .message-content {
          flex: 1;
          margin-left: 10px;
          align-items: center;
          display: flex;
          justify-content: flex-end;
        }
        .content-inner {
          background: #2d65f7;
          border-radius: 5px;
          padding: 10px;
          color: #fff;
        }
      }
      .ai-item {
        line-height: 23px;
        .message-content {
          display: block;
          background: #fff;
          border-radius: 5px;
        }
        .user-icon {
          background: #64018f;
          margin-left: 0px;
        }
        :deep(.md-editor-previewOnly) {
          border-radius: 5px;
          background: #fff;
        }
        :deep(.md-editor-preview-wrapper) {
          padding: 10px;
        }
        .loading {
          text-align: center;
        }
      }
    }
  }
  .send-panel {
    position: relative;
    margin: 5px auto 0px;
    width: 800px;
    background: #fff;
    border-radius: 5px;
    padding: 10px;
    .send-btn {
      text-align: right;
      margin-bottom: 0px;
      padding: 5px;
      :deep(.el-form-item__content) {
        justify-content: flex-end;
      }
    }
    :deep(.el-textarea__inner) {
      border: 0 !important;
      resize: none !important;
      box-shadow: none;
    }
  }
}
.no-data {
  text-align: center;
  color: #5f5f5f;
}

.assignment-header {
    display: flex;
    height: 7lvh; /* 导航栏高度 */
    width: 99lvw;
    background-color: #13227A;
    color: white;
    align-items: center; /* 垂直居中对齐 */
}

.back-button {
    background-color: transparent;
    width: 25px; 
    height: 25px; 
    color: white;
    cursor: pointer;
}

.back-icon {
    width: 25px; 
    height: 25px; 
}

.information {
    font-size: 28px;
    line-height: 7lvh;
    font-family: kaiti;
    margin-left: 42%;
    color: rgb(243, 245, 254);
}

.user-info {
  position: relative;
  align-items: center;
  cursor: pointer;
  display: flex;
  margin-left: 36%;
  z-index: 999;
}

.avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  margin-right: 10px;
}

.dropdown-arrow {
  width: 16px;
  height: 16px;
  margin-left: 5px;
}

.username22 {
  font-size: 16px;
}

.dropdown-menu {
  position: absolute;
  top: 100%;
  right: 0;
  background-color: white;
  color: black;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 10px;
  z-index: 1000;
}

.dropdown-menu :hover {
  background-color: #f0f0f0;
  color: brown;
}
</style>
